import { Component , EventEmitter } from '@angular/core';
import { NavController, NavParams , ToastController ,App } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { BifrostProvider } from '../../providers/bifrost/bifrost';
import { RegisterPage } from '../register/register';

/**
 * Generated class for the LoginPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {


  public user : string;
  public pwd : string;
  constructor(
    public navCtrl: NavController, 
    public navParams: NavParams,
    private toast : ToastController,
    private storage : Storage,
    private bifrost : BifrostProvider,
    private app : App
  ) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad LoginPage');
  }

  public login(){
    if(!this.user || !this.pwd){
      this.emitTost('用户名或密码不能为空');
      return;
    }
    if(this.user.trim().length == 0){
      this.emitTost('用户名不能为空');
      return;
    }
    if(this.pwd.trim().length == 0){
      this.emitTost('密码不能为空');
      return;
    }
    this.storage.get(this.user.trim()).then(res=>{
      if(res == this.pwd.trim()){
        this.emitTost('登录成功');
        this.bifrost.loginPass.emit(true);
        this.storage.set('isLogin',true);
      }else{
        this.emitTost('用户名或者密码错误');
      }
    })
    
  }

  public regist(){
    this.app.getRootNav().push(RegisterPage);
  }

  private emitTost (message){
    let toast = this.toast.create({
        message : message,
        duration : 2000,
        position : 'top'
    });
    toast.present();
  }

}
